package dao;
import service.ResourceService;
import domin.Resource;
import domin.RoleAssResource;
import lombok.extern.slf4j.Slf4j;
import util.JdbcHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.TreeSet;

@Slf4j
public class RoleAssResourceDao {
    private static RoleAssResourceDao roleAssResourceDao = new RoleAssResourceDao();
    private RoleAssResourceDao(){}
    public static RoleAssResourceDao getInstance(){
        return roleAssResourceDao;
    }

    public Collection<RoleAssResource> findAll(Connection connection, int roleId) throws SQLException {
        Collection<RoleAssResource> roleAssResources = new TreeSet<RoleAssResource>();
        String sql_select_all = "SELECT * FROM roleassresource WHERE role_id = ?";
        PreparedStatement pstmt_select_all =
                connection.prepareStatement(sql_select_all);
        pstmt_select_all.setInt(1, roleId);
        ResultSet resultSet_select_all = pstmt_select_all.executeQuery();
        while (resultSet_select_all.next()) {
            int id = resultSet_select_all.getInt("id");
            int role_id = resultSet_select_all.getInt("role_id");
            int resourceId = resultSet_select_all.getInt("resource_id");
            Resource resource = ResourceService.getInstance().find(resourceId);
            RoleAssResource roleAssResource =
                    new RoleAssResource(id, null, resource);
            roleAssResources.add(roleAssResource);
        }
        JdbcHelper.close(resultSet_select_all, pstmt_select_all);
        return roleAssResources;
    }
}
